package com.efounder.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AlertDialog;

import android.util.Log;

import com.core.xml.StubObject;
import com.efounder.activity.TabBottomActivity;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.chat.model.Constant;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JResponseObject;
import com.efounder.model.APKUpdateManager;
import com.efounder.model.LoginUtil;
import com.efounder.model.LoginUtilInterface;
import com.efounder.ospmobilelib.R;
import com.efounder.utils.FilesOperationDataUtil;
import com.efounder.utils.ResStringUtil;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SAVE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;
import static com.efounder.frame.utils.Constants.KEY_SIGN;
import static com.efounder.frame.utils.Constants.KEY_TANGZU_JSRQ;

/**
 * 这是使用平台PO登录的类
 */
public class LoginManager {
    //	StorageUtil storageUtil;
    private String userName, passWord;
    private Context mContext;
    public final String KEY_MENU_ROOT = "menuRoot";
    private String chatUserID;
    private String chatPassword;
    Map<?, ?> responseMap;
    private JResponseObject pingtaiRO;
    private Map<?, ?> pingtaiResponseMap;
    private APKUpdateManager apkUpdateManager = new APKUpdateManager();
    JResponseObject loginRO;
    StorageUtil storageUtil;

    //是否是第一次登陆使用 true 登陆界面调用 false时 自动登陆或手动检测更新传false
    private boolean isLoginUsed;

    public LoginManager(boolean isLoginUsed) {
        this.isLoginUsed = isLoginUsed;
    }

    /**
     * 第一步 登录
     *
     * @param context
     * @param userName1
     * @param passWord1
     * @param isCheckUpdate 手动更新时 没有最新版本toast
     */
    public void loginBegin(final Context context, String userName1, final String passWord1, final boolean isCheckUpdate) {
        mContext = context;
        userName = userName1;
        passWord = passWord1;
        storageUtil = new StorageUtil(context, "storage");

        //TODO 此处初始化EAI，具体位置，以后再考虑下。

        EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);

        EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
        EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
        EAI.Path = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);
        EAI.Service = Constant.EAI_SERVICE;


        storageUtil.putString("address", EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS));
        storageUtil.putString("port", EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT));
        storageUtil.putString("path", EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH));
        storageUtil.putString("APPID", EnvironmentVariable.getProperty(KEY_SETTING_APPID));
        storageUtil.putString("sign", EnvironmentVariable.getProperty(KEY_SIGN));
        storageUtil.putString("service", "ZYYT_DB01");
        // service = "ZYYT_DB01";
        storageUtil.commit();


        LoginUtil loginUtil = new LoginUtil();
        loginUtil.start(userName, passWord,
                new LoginUtilInterface() {
                    @Override
                    public void startProgress() {
                        if (isCheckUpdate) {
                            LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_checking));
                        } else {
                            LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_islogining));
                        }
                    }

                    @Override
                    public void loginSuccess(JResponseObject result) {
                        /**用户登录名和密码储存在EV中**/
                        EnvironmentVariable.setUserName(userName);
                        EnvironmentVariable.setPassword(passWord);
                        Map<?, ?> responseMap = result.getResponseMap();
                        if (responseMap == null) {
                            if (isCheckUpdate) {
                                ToastUtil.showToast(mContext, ResStringUtil.getString(R.string.common_text_chcek_version_fail));
                            } else {
                                //showDialog("登录失败，请联系管理员。");
                                showDialog(ResStringUtil.getString(R.string.common_text_login_fail_please_wait));

                            }
                            return;
                        } else {
                            pingtaiRO = (JResponseObject) responseMap.get("pingtai");
                        }
                        if (pingtaiRO != null) {
                            pingtaiResponseMap = pingtaiRO.getResponseMap();
                        } else {
                            if (isCheckUpdate) {
                                ToastUtil.showToast(mContext, ResStringUtil.getString(R.string.common_text_chcek_version_fail));
                            } else {
                                //showDialog("登录失败，请联系管理员。");
                                showDialog(ResStringUtil.getString(R.string.common_text_login_fail_please_wait));
                            }
                            return;
                        }

                        /**以下变量也存在EV中**/
//						Map<String, String> userInfoMap = (Map<String, String>) pingtaiResponseMap.get("UserInfo");
//						EnvironmentVariable.setEmail(userInfoMap.get("F_EMAIL"));
//						EnvironmentVariable.setF_DWMC(userInfoMap.get("F_DWMC"));


                        //开始检查是否更新版本
                        loginRO = result;
//						CheckAPKVerion(result);
                        boolean update = apkUpdateManager.CheckAPKVerion(mContext, result, msgHandler);
                        if (isCheckUpdate && !update) {
                            ToastUtil.showToast(context, R.string.common_text_app_is_newest);
                        }
                    }

                    @Override
                    public void loginFailed(String errorString) {

                        //有可能网络出错了---- 密码错误
                        showDialog(errorString + "");
                        //ToastUtil.showToast(mContext, errorString + "");
                        LoadingDataUtilBlack.dismiss();
                    }

                    @Override
                    public void exception(String excptionString) {
                        showDialog(excptionString + ResStringUtil.getString(R.string.login_manager_retry));
                        //ToastUtil.showToast(mContext, excptionString + "，请重试。");
                        LoadingDataUtilBlack.dismiss();
                    }
                }
        );
    }


    private MsgHandler msgHandler = new MsgHandler();

    class MsgHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                case 2:
                    CheckIM(loginRO);
                    break;
            }
        }
    }

    /**
     * 第四步 检查是否是微信用户
     */
    private void CheckIM(JResponseObject result) {
        if (isLoginUsed) {
            boolean isIMUser = isIMUser(result);
            if (isIMUser) {
                //检查权限
                //铁工独有的功能权限，上面是平台的功能权限检查。
                String gnqxSetttingModel = EnvironmentVariable.getProperty("GNQXSET");
                if (null != gnqxSetttingModel && gnqxSetttingModel.equals("0")) {
                    //checkGNQXBYOSP(result);
                    checkGNQXBYOSP(pingtaiResponseMap);
                } else {
                    checkGNQX(result);
                }

                //处理聊天的权限
                checkChatPermission(result);


                mHandler.sendEmptyMessage(0);

            } else {
                //FIXME 由于铁工没有注册功能，先屏蔽掉-- 跳转到注册界面，并传值
//			Intent intent = new Intent(mContext, RegisterActivity.class);
//			intent.putExtra("userName",userName);
//			intent.putExtra("password",passWord);
//			mContext.startActivity(intent);
            }
        }
    }

    /**
     * @param result
     * @return
     */
    private boolean isIMUser(JResponseObject result) {
        //判断是否注册
        Map<?, ?> responseMap = (Map<?, ?>) result.getResponseMap();
        EFDataSet weChatDataSet = (EFDataSet) responseMap.get("extrawx");
        if (weChatDataSet == null) {
            LoadingDataUtilBlack.dismiss();
            //Toast.makeText(mContext, "没有该用户", Toast.LENGTH_LONG).show();
            showDialog(ResStringUtil.getString(R.string.login_user_not_exist));
            return false;
        }
        List<EFRowSet> weChatEfRowSets = weChatDataSet.getRowSetArray();
        EFRowSet weChatRowSet = weChatEfRowSets.get(0);
        chatUserID = weChatRowSet.getString("F_IM_USERID", "");
        chatPassword = weChatRowSet.getString("F_IM_PASSWORD", "");

        String group_id = weChatRowSet.getString("group_id", "");
        EnvironmentVariable.setProperty(chatUserID + "workgroup", group_id);


        if (chatUserID == null || chatUserID.equals("")) {
            LoadingDataUtilBlack.dismiss();

            showDialog(ResStringUtil.getString(R.string.login_manager_user_not_exist));
            //Toast.makeText(mContext, "该用户没有注册，请先注册用户", Toast.LENGTH_LONG).show();

            return false;
        }

        //
        //TODO 如果是普光应用,需要保存以下信息,根据配置文件决定是否保存 yqs
        if ("true".equals(EnvironmentVariable.getProperty(KEY_SAVE))) {
            saveUserInfo(weChatRowSet);
        }

        //TODO 如果是糖足应用判断是否需要完善信息 yqs
        if ("OSPMobileTZu".equals(EnvironmentVariable.getProperty(KEY_SETTING_APPID))) {
            //存储用户信息
            TangZuUtil.saveTangZuInfo(weChatRowSet);
            //判断是否需要完善

            String jsrq = EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ, "");
            if ("3".equals(jsrq) || "9".equals(jsrq) || "2".equals(jsrq) || "7".equals(jsrq)
                    || "10".equals(jsrq) || "13".equals(jsrq)) {
                //3表示患者
                String shengao = weChatRowSet.getString("F_SFZZP", "");
                String tizhong = weChatRowSet.getString("F_SFZFMZP", "");
                if ("".equals(shengao) || "".equals(tizhong)) {
                    EnvironmentVariable.setProperty("NEED_EDIT", "true");//病人需要完善自己的信息
                } else {
                    EnvironmentVariable.setProperty("NEED_EDIT", "false");//病人不需要完善自己的信息
                }
            }
        }
        return true;
    }

    /**
     * 存储用户信息，以便全局使用
     *
     * @param weChatRowSet
     */
    private void saveUserInfo(EFRowSet weChatRowSet) {
        String userNameLast = storageUtil.getString("userName");
        if (userNameLast != "" && !userName.equals(userNameLast)) {
            FilesOperationDataUtil.clearFileData(mContext);
        }
        storageUtil.putString("userName", userName);
        storageUtil.putString("passWord", passWord);

        if (weChatRowSet != null) {
            String loginUserID = weChatRowSet.getString("F_ZGBH", "");//编号例如 P0034
            String loginUserName = weChatRowSet.getString("F_NAME", "");//用户名 例如冯继盛

            storageUtil.putString("loginUserID", loginUserID);
            storageUtil.putString("loginUserName", loginUserName);
            // EnvironmentVariable.setEmail();
            AndroidEnvironmentVariable.setEmail(weChatRowSet.getString("F_EMAIL", ""));
            AndroidEnvironmentVariable.setPassword(passWord);
            AndroidEnvironmentVariable.setF_DWMC(weChatRowSet.getString("F_DWMC", ""));
            AndroidEnvironmentVariable.setUserName(weChatRowSet.getString("F_NAME", ""));
            AndroidEnvironmentVariable.setUserID(userName);
        }

        storageUtil.commit();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //在微信登陆之前，存储用户名，密码
            //FIXME 在底层库用到getUserID方法，以后再修改
            EnvironmentVariable.setUserID(chatUserID);
            EnvironmentVariable.setProperty("unIMUserId", chatUserID);
            EnvironmentVariable.setProperty("unIMPassword", chatPassword);
            Log.i("------", "EnvironmentVariable------" + EnvironmentVariable.getProperty(CHAT_USER_ID));
            Log.i("------", "EnvironmentVariable------" + EnvironmentVariable.getProperty(CHAT_PASSWORD));
            startMainActivity();
        }
    };


    /**
     * 启动免责声明
     *
     * @param enterName
     * @throws ClassNotFoundException
     */
    private void launchMZSMActivity(String enterName) throws ClassNotFoundException {

        Class<?> aClass = Class.forName("com.efounder.activity.DisclaimerActivity");
        Intent intent = new Intent(mContext, aClass);
        intent.putExtra("enterName", enterName);
        mContext.startActivity(intent);
    }

    private void startMainActivity() {

        //todo 处理糖足应用跳转完善信息界面
        String jsrq = EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ);
        if (jsrq != null && "true".equals(EnvironmentVariable.getProperty("NEED_EDIT"))) {
            String enterName = null;
            if ("3".equals(jsrq)) {
                //患者完善
                enterName = "SDPerfectDiabeteInfo";
            } else if (("9".equals(jsrq) || "2".equals(jsrq) || "13".equals(jsrq) || "7".equals(jsrq))) {
                //医生完善
                enterName = "SDPerfectDoctorInfo";
            } else if ("10".equals(jsrq)) {
                //助理完善
                enterName = "SDPerfectAssistantInfo";

            }
            try {

                launchMZSMActivity(enterName);
                ((Activity) mContext).finish();
                mContext = null;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                Log.e(this.getClass().getName(), ResStringUtil.getString(R.string.login_manager_user_not_exist));
            }

            return;
        }

        //真正的存储IM用户名密码
        EnvironmentVariable.setUserID(chatUserID);
        EnvironmentVariable.setProperty(CHAT_USER_ID, chatUserID);
        EnvironmentVariable.setProperty(CHAT_PASSWORD, chatPassword);


        try {
            LoadingDataUtilBlack.dismiss();
            String className = mContext.getResources().getString(R.string.from_group_backto_first);
            Class clazz = Class.forName(className);
            Intent myIntent = new Intent(mContext, clazz);
            myIntent.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级

            mContext.startActivity(myIntent);
            ((Activity) mContext).finish();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        //ESPMobile处理
//        Intent intent1 = new Intent(mContext, TabBottomActivity.class);
//        intent1.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级
//        //intent1.putExtra("listobj", (Serializable) mainMenuList);
//        mContext.startActivity(intent1);
//        ((Activity) mContext).finish();
//        mContext = null;
//        LoadingDataUtilBlack.dismiss();

    }

    public static void checkGNQX(JResponseObject ro) {
        Map<?, ?> responseMap = ro.getResponseMap();
        EFDataSet weChatDataSet = (EFDataSet) responseMap.get("extrawx");
        if (weChatDataSet.getDataSetMap() == null) {
            EnvironmentVariable.setProperty("gnqx", null);
            return;
        }
        EFDataSet GNQXDataSet = weChatDataSet.getDataSetMap().get("GNQX");
        StringBuffer gnqxBuffer = new StringBuffer("无");
        //String gnqxString = "无";
        if (GNQXDataSet != null && GNQXDataSet.getRowSetList() != null && GNQXDataSet.getRowSetList().size() != 0) {
            // gnqxString = "";
            gnqxBuffer = new StringBuffer("");
            for (int i = 0; i < GNQXDataSet.getRowSetList().size(); i++) {
                EFRowSet efRowSet = GNQXDataSet.getRowSet(i);
                String gnqx = (String) efRowSet.getDataMap().get("F_GNBH");
                gnqxBuffer.append(gnqx).append(";");
                //gnqxString = gnqxString + gnqx + ";";
            }
        }
        //设置权限
        //EnvironmentVariable.setProperty("gnqx", gnqxString);
        EnvironmentVariable.setProperty("gnqx", gnqxBuffer.toString());
    }

    public static void checkGNQXBYOSP(Map pingtaiResponseMap) {
        //	Map<?, ?> responseMap = ro.getResponseMap();
        //EnvironmentVariable.setProperty("gnqx","GDSAPP01;");

        // String gnqxString = "";
        StringBuffer gnqxBuffer = new StringBuffer("");

        StubObject stubObject = (StubObject) pingtaiResponseMap.get("SecurityContext");
        if (stubObject == null) {
            return;
        }

        Hashtable<?, ?> hashtable = stubObject.getStubTable();
        ArrayList<String> qnqxList = (ArrayList<String>) hashtable.get(EnvironmentVariable.getUserName());
        if (qnqxList == null) {
            return;
        }
        for (int i = 0; i < qnqxList.size() - 1; i++) {
            if (i < qnqxList.size() - 2) {
                gnqxBuffer.append(qnqxList.get(i)).append(";");
                //gnqxString = gnqxString + qnqxList.get(i) + ";";
            } else {
                //gnqxString = gnqxString + qnqxList.get(i);
                gnqxBuffer.append(qnqxList.get(i));

            }

        }
        if ("".equals(gnqxBuffer.toString())) {
            return;
        }
//        EnvironmentVariable.setProperty("gnqx", gnqxString);
        EnvironmentVariable.setProperty("gnqx", gnqxBuffer.toString());

    }

    public static void checkChatPermission(JResponseObject ro) {
        Map<?, ?> responseMap = ro.getResponseMap();
        EFDataSet weChatDataSet = (EFDataSet) responseMap.get("extrawx");

        if (weChatDataSet == null) {
            return;
        }

        List<EFRowSet> weChatEfRowSets = weChatDataSet.getRowSetArray();
        EFRowSet weChatRowSet = weChatEfRowSets.get(0);
        String chatpermission = weChatRowSet.getString("chatpermission", "");
        EnvironmentVariable.setProperty("chatpermission", chatpermission);



    }


    public void showDialog(String info) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (!((Activity) mContext).isDestroyed()) {

                new AlertDialog.Builder(mContext).
                        setMessage(info).setTitle(R.string.common_text_hint)
                        .setPositiveButton(R.string.common_text_confirm, null).show();
            }
        } else {
            if (((Activity) mContext) != null && !((Activity) mContext).isFinishing()) {
                new AlertDialog.Builder(mContext).
                        setMessage(info).setTitle(R.string.common_text_hint)
                        .setPositiveButton(R.string.common_text_confirm, null).show();
            }
        }
    }
}
